package data_structur.Stack;

public class ArrayStackDemo {

    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(10);
        arrayStack.push(88);
        arrayStack.push(101);
        arrayStack.push(20);
        arrayStack.push(15);
        arrayStack.push(47);
        arrayStack.push(56);
        arrayStack.push(78);
        arrayStack.push(12);
        arrayStack.push(33);
        arrayStack.push(48);
        arrayStack.push(120);
        arrayStack.list();
        System.out.println(arrayStack.pop());
        arrayStack.list();
    }

}

/**
 * 使用数组来模拟栈的实现
 */
class ArrayStack {
    private int maxSize;// 栈容量
    private int[] stack;// 数组模拟栈
    private int top;// 栈顶指针

    public ArrayStack(int maxSize){
        if (maxSize < 1){
            System.out.println("Given size is too small, initial failed.");
            return;
        }
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
        this.top = -1;
    }

    public boolean isFull(){
        return this.top == this.maxSize - 1;
    }

    public boolean isEmpty(){
        return this.top == -1;
    }

    public void push(int value){
        if (isFull()){
            System.out.println("Stack is full, failed to push");
            return;
        }
        this.top++;
        this.stack[this.top] = value;
    }

    public int pop(){
        if (isEmpty()){
            throw new RuntimeException("Stack is empty, failed to pop");
        }
        int pop = this.stack[this.top];
        this.top--;
        return pop;
    }

    public void list(){
        if (isEmpty()){
            System.out.println("Stack is empty, failed to list.");
            return;
        }
        for (int i = this.top; i >= 0; i--) {
            System.out.println("stack["+ i +"] = " + this.stack[i]);
        }
    }
}